package com.wanmait.cookbook.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


import com.wanmait.cookbook.vo.Works;
import com.wanmait.demo.util.DBHelper;

/*
 * 点赞表DAO
 */
public class LikeDAO {
	private LikeDAO() {}
	private static LikeDAO likeDAO = new LikeDAO();
	public static LikeDAO getLikeDAO() {
		return likeDAO;
	}
	public int getLikeCountByWorks(Works works) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			String sql = "SELECT count(*) c FROM `like` " 
					+ " WHERE works_id=? ";
			conn = DBHelper.getHelper().getConn();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, works.getId());
			rs = ps.executeQuery();
			rs.next();
			int row = rs.getInt("c");
			return row;
			
		}catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBHelper.getHelper().closeConn(rs, ps, conn);
		}
		return 0;
	}
	
	/**
	 *  判断是否点赞作品
	 * @param userinfoId
	 * @param worksId
	 * @return
	 */
	public boolean judgeWorksLike(Integer userinfoId,Integer worksId) {
	    Connection conn = null;
	    PreparedStatement ps = null;
	    ResultSet rs = null;
	    String sql = "SELECT * from `like` WHERE userinfo_id=? AND works_id=?";
	    try {
	      conn = DBHelper.getHelper().getConn();
	      ps = conn.prepareStatement(sql);
	      ps.setInt(1, userinfoId);
	      ps.setInt(2, worksId);
	      rs = ps.executeQuery();
	      return rs.next();
	    } catch (SQLException e) {
	      // TODO Auto-generated catch block
	      e.printStackTrace();
	    }
	    finally {
	      DBHelper.getHelper().closeConn(rs, ps, conn);
	    }
	    return false;
	  }
	
	/**
	 *  作品添加点赞
	 * @param userinfoId
	 * @param worksId
	 */
	public void addWorksLike(Integer userinfoId,Integer worksId) {
		String sql = "INSERT INTO `like`(works_id,userinfo_id) VALUES(?,?)";
		DBHelper.getHelper().executeUpdate(sql, worksId,userinfoId);
	}
	
	/**
	 *  作品取消点赞
	 * @param userinfoId
	 * @param worksId
	 */
	public void cancelWorksLike(Integer userinfoId,Integer worksId) {
		String sql = "DELETE FROM `like` WHERE userinfo_id=? AND works_id=?";
		DBHelper.getHelper().executeUpdate(sql, userinfoId,worksId);
	}
	
}
